<?php

namespace app\common\service;

use EasyWeChat\Factory;

class WechatService
{
    protected $app;

    public function __construct()
    {
        $config = [
            'app_id' => 'wxb14fa06617f17c5e',
            'secret' => 'c4e5d90725bf23e927db07bfb7f69e0f',
        ];

        $this->app = Factory::miniProgram($config);
    }


    /**
     * 获取用户信息
     * @param string $code
     * @return array
     */
    public function getUserIdByCode(string $code) : array
    {
    
        try {
            $session = $this->app->auth->session($code);

            return $session;
        } catch (\Exception $e) {
            // 处理错误，比如 code 无效或已过期
            return [
                'code' => $e->getCode(),
                'msg'=> $e->getMessage(),
            ];
        }
    }

    // 给小程序用户推送模板消息
    public function sendTplMsg(string $openid, string $content) : array
    {
        $data = [
            'touser' => $openid,
            'template_id' => 'ZhYvCPxMD0e143496nj4ou9_Ntbp1MWGwGWVd4vbYOc',
            'page' => 'pages/index/index',
            'miniprogram_state' => 'developer',
            'data' => [
                'thing3' => [
                    'value' => '联系人',
                ],
                'time2' => [
                    'value' => date('Y-m-d H:i:s'),
                ],
                'thing6' => [
                    'value' => 'liucunzhou',
                ],
                'thing1' => [
                    'value' => $content,
                ],
            ],
        ];

        $result = $this->app->subscribe_message->send($data);

        return $result;
    }

}
